package com.liang.demo.service.impl;

import com.liang.demo.dto.MenuDto;
import com.liang.demo.mapper.MenuMapper;
import com.liang.demo.mapper.RoleMapper;
import com.liang.demo.po.Menu;
import com.liang.demo.po.Role;
import com.liang.demo.service.MenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 陈琪亮
 * @version 1.0
 * @date 2021/3/19 16:41
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<MenuDto> selectByAdminId(Long id) {
        //先查询用户有什么角色
        //再通过角色查询用户有什么菜单
        List<Role> roles = roleMapper.selectByAdminId(id);
        List<Menu> menus = new ArrayList<>();
        List<MenuDto> menu_parent_dto = new ArrayList<>();
        roles.forEach(r -> {
            //先获取父菜单
            List<Menu> menu_parent = menuMapper.selectByRoleId(r.getId(), 1);
            //再通过父菜单获取子菜单
            menu_parent.forEach(m -> {
                MenuDto menuDto_parent = new MenuDto();
                BeanUtils.copyProperties(m, menuDto_parent);
                menu_parent_dto.add(menuDto_parent);

                List<MenuDto> menu_child_dto = new ArrayList<>();
                List<Menu> menu_child = menuMapper.selectByParentId(m.getId(), 2);
                menu_child.forEach(mm -> {
                    MenuDto menuDto_child = new MenuDto();
                    BeanUtils.copyProperties(mm, menuDto_child);
                    menu_child_dto.add(menuDto_child);
                });
                menuDto_parent.setChildren(menu_child_dto);
            });

        });
        return menu_parent_dto;
    }

    @Override
    public List<Menu> getMenuList(Long adminId) {
        return menuMapper.getMenuList(adminId);
    }

    @Override
    public List<Menu> getMenuAll() {
        return menuMapper.getMenuAll();
    }
}
